import {
	warn
} from "console";
import {
	defineStore
} from "pinia";
import {
	websocketUrl
} from '../utils/config.js'

const MAXCONNECT = 10;
export const useWebsocket = defineStore({
	id: "use-Websocket",
	state: () => {
		return {
			userName: '',
			//链接是否打开了
			isOpen: false,
			// socketTask
			socketTask: false,
			//绑定的fd
			bindFd: null,
			// 当前聊天对象（进入聊天页面获取）
			network: true,
			//断线重连定时器
			timer: null,
			//心跳间隔
			timeout: 5000,
			//心跳事件
			interval: null,
			// 当前重连次数
			connectNum: 0,
			type: 1,
			serverTimeoutObj: null,
			severTimeout: 10000,
			newObj: {}

		}
	},

	getters: {},
	actions: {
		setName(name) {

			this.userName = name
			this.initWebsocket(name)
		},
		setType(id) {
			this.type = id

		},
		initWebsocket(name) {

			if (this.isOpen) {
				return;
			}
			var that = this
			uni.getNetworkType({
				success(result) {
					if (result.networkType !== 'none') {

						const wsurl = websocketUrl + `${name}`;
						this.socketTask = uni.connectSocket({
							url: wsurl,
							success: e => {
								console.log("connect success ", e)
							},
							fail: e => {
								console.log("connect fail ", e)
							},
							complete: (e) => {

							},
						});
						if (!this.socketTask) {
							return;
						};
						this.socketTask.onOpen(() => {
							if (this.timer) {
								clearTimeout(this.timer);
								this.timer = null
							}
							if (this.serverTimeoutObj) {
								clearTimeout(this.serverTimeoutObj)
								this.serverTimeoutObj = null
							}

							this.isOpen = true;

							const msg = `getTotalNews`
							uni.sendSocketMessage({
								data: msg,
								fail: function(e) {
									// console.log("send " + msg + " fail ", e)
								},
								success: function(e) {
									// console.log("send " + msg + " success ", e)
								},
							})

							that.heartCheck();
						})

						this.socketTask.onMessage(e => {
							if (e.data === 'PONG') {
								that.heartCheck()
							} else {
								// console.log("onMessage", e.data)
								let res = JSON.parse(e.data);
								// 接受
								that.newObj = res
								console.log('res',that.newObj)
							}
						})

						// 监听关闭
						this.socketTask.onClose((res) => {
							const code = res.code;
							const reason = res.reason;
							console.log("onClose", res, code)
							this.isOpen = false;
							//清除定时器
							clearTimeout(this.timer);
							if (this.timeoutObj) {
								clearTimeout(this.timeoutObj)
							}
							if (this.serverTimeoutObj) {
								clearTimeout(this.serverTimeoutObj)
							}
							this.timer = null
							if (!(code === 1000 && reason === 'logout')) {
								that.reConnect()
							}
						});
						// 监听错误
						this.socketTask.onError((e) => {
							that.wsClose({
								code: 4001,
								reason: e
							})

						});

					} else {
						this.netWork = false;
						// 网络断开后显示model
						uni.showModal({
							title: '网络错误',
							content: '请重新打开网络',
							showCancel: false,
							success: function(res) {
								if (res.confirm) {}
							}
						})
					}
				}
			})



		},
		// 关闭连接
		wsClose(info) {

			const code = info.code
			const reason = info.reason
			if (this.isOpen) {
				this.isOpen = false;
			}
			if (this.socketTask) {
				try {
					this.socketTask.close({
						code,
						reason,
						success: (e) => {
							console.log("close success ", e)
						},
						fail: (e) => {
							if (this.timeoutObj) {
								clearTimeout(this.timeoutObj)
							}
							if (this.serverTimeoutObj) {
								clearTimeout(this.serverTimeoutObj)
							}
							this.isOpen = false;
							//清除定时器
							clearTimeout(this.timer);
							this.timer = null
							that.reConnect();
				
						}
					});
				} catch (e) {
					console.log("close error", e)
				}

			}
		},
		heartCheck() {
			var that = this
			if (this.timeoutObj) {
				clearTimeout(this.timeoutObj)
			}
			if (this.serverTimeoutObj) {
				clearTimeout(this.serverTimeoutObj)
			}

			this.timeoutObj = setTimeout(() => {
				uni.sendSocketMessage({
					data: 'PING',
					fail: function(e) {


						that.wsClose({
							code: 4003,
							reason: '心跳发送失败'
						})
					},
					success: function(e) {
						if (this.serverTimeoutObj) {
							clearTimeout(this.serverTimeoutObj)
						}
						this.serverTimeoutObj = setTimeout(function() {

							that.wsClose({
								code: 4002,
								reason: '长时间未收到pong'
							})
						}, this.severTimeout);
					},
				});
			}, this.timeout)



		},

		// 心跳
		reConnect() {
			var that = this
			if (this.timer) {
				clearTimeout(this.timer)
				this.timer = null
			}

			if (this.connectNum < MAXCONNECT) {
				this.timer = setTimeout(() => {

					this.initWebsocket(this.userName)
				}, 1000 * 3)
				this.connectNum += 1;
			} else if (this.connectNum < MAXCONNECT + 10) {
				this.timer = setTimeout(() => {

					this.initWebsocket(this.userName)
				}, 1000 * 10)
				this.connectNum += 1;
			} else if (this.connectNum < MAXCONNECT + 20) {
				this.timer = setTimeout(() => {
					this.initWebsocket(this.userName)
				}, 1000 * 60)
				this.connectNum += 1;
			} else if (this.connectNum < MAXCONNECT + 30) {
				this.timer = setTimeout(() => {
					this.initWebsocket(this.userName)
				}, 1000 * 60 * 10)
				this.connectNum += 1;
			} else {
				this.timer = setTimeout(() => {
					this.initWebsocket(this.userName)
				}, 1000 * 60 * 30)
				this.connectNum += 1;
			}
		}
	}
});